﻿// ComPortSet.cpp: 实现文件
//

#include "stdafx.h"
#include "ComPortSet.h"
#include "afxdialogex.h"
#include "Resource.h"
#include "myUtil.h"
#include <fstream>


// ComPortSet 对话框

IMPLEMENT_DYNAMIC(ComPortSet, CDialogEx)

ComPortSet::ComPortSet(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_DIALOG_PORT_SET_DLG, pParent)
{
	portSetTargetName = "";
}

BOOL ComPortSet::OnInitDialog()
{
	GetDlgItem(IDC_STATIC_SET_FOR)->SetWindowText(portSetTargetName);
	CDialogEx::OnInitDialog();
	int com = 0;
	int baud = 0;
	if (portSetTargetName == mcuSet)
	{
		myUtil::getMcuComSets();
		com = myUtil::mcuCom;
		baud = myUtil::mcuBaud;
	}
	else
	{
		myUtil::getMeterComSets();
		com = myUtil::meterCom;
		baud = myUtil::meterBaud;
	}


	for (int i = 0; i <= 9; ++i)
	{
		TCHAR comName[32];
		wsprintf(comName, L"COM %d", i);
		m_PortCombobox.InsertString(m_PortCombobox.GetCount(), comName);
	}
	m_PortCombobox.SetCurSel(com);

	int baudRate[] = { 9600, 19200, 115200 };
	for (int i = 0; i < ARRAYSIZE(baudRate); ++i)
	{
		TCHAR brateName[32];
		wsprintf(brateName, L"%d", baudRate[i]);
		m_BaudrateCombobox.InsertString(m_BaudrateCombobox.GetCount(), brateName);
	}
	if(baud == 9600)
		m_BaudrateCombobox.SetCurSel(0);
	else if(baud == 19200)
		m_BaudrateCombobox.SetCurSel(1);
	else
		m_BaudrateCombobox.SetCurSel(2);
	if (portSetTargetName == mcuSet)
	{
		std::ifstream iif(mcuConFile);
		if (iif.is_open())
		{
			int portNumberIndex, baudRateIndex;
			iif >> portNumberIndex;
			iif >> baudRateIndex;
			m_PortCombobox.SetCurSel(portNumberIndex);
			m_BaudrateCombobox.SetCurSel(baudRateIndex);
		}
	}
	else
	{
		std::ifstream iif(meterConFile);
		if (iif.is_open())
		{
			int portNumberIndex, baudRateIndex;
			iif >> portNumberIndex;
			iif >> baudRateIndex;
			m_PortCombobox.SetCurSel(portNumberIndex);
			m_BaudrateCombobox.SetCurSel(baudRateIndex);
		}
	}
	return true;
}


ComPortSet::~ComPortSet()
{
}

void ComPortSet::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATIC_SET_FOR, setDlgFor);
	DDX_Control(pDX, IDC_COMBO_COMPORT, m_PortCombobox);
	DDX_Control(pDX, IDC_COMBO_BAUD, m_BaudrateCombobox);
}


BEGIN_MESSAGE_MAP(ComPortSet, CDialogEx)
	ON_BN_CLICKED(IDC_BUTTON_APPLY, &ComPortSet::OnBnClickedButtonApply)
END_MESSAGE_MAP()


// ComPortSet 消息处理程序


void ComPortSet::OnBnClickedButtonApply()
{
	// TODO: 在此添加控件通知处理程序代码
	CString port;
	m_PortCombobox.GetWindowTextW(port);
	CString baudRate;
	m_BaudrateCombobox.GetWindowTextW(baudRate);

	int portNumber = 0;
	const int spaceIdx = port.Find(L" ");
	if (spaceIdx > 0)
		portNumber = _wtoi(&port.GetBuffer()[spaceIdx]);
	
	if (portSetTargetName == mcuSet)
	{
		std::ofstream of(mcuConFile);
		if (of.is_open())
		{
			of << portNumber << std::endl << _wtoi(baudRate);
		}
	}
	else
	{
		std::ofstream of(meterConFile);
		if (of.is_open())
		{
			of << portNumber << std::endl << _wtoi(baudRate);
		}
	}
	CDialogEx::OnOK();
}
